<template>
  <div class="container">
    <div class="header flex-yc flex-xbt">
      <h2>文章列表</h2>
    </div>
    <table-comp :column="column" index :list="dataBaseArticles">
      <template v-slot:handleSlot="{ row }">
        <el-button size="small" type="success" @click="onAddArticle(row)">
          编辑
        </el-button>
        <el-button size="small" type="danger" @click="onDelArticle(row.id)">
          删除
        </el-button>
      </template>
    </table-comp>
  </div>
</template>

<script setup lang="ts">
import TableComp from '@/components/table/index.vue'
import {
  reqDeleteDataBaseArticle,
  reqGetDataBaseArticles,
  reqGetDataBaseTemplate,
} from '@/api/database.ts'
import { onMounted, ref } from 'vue'
import { respDataBaseArticle, respDataBaseTemplate } from '@/api/types/database'
import { reactive } from 'vue'
import { tableColumn } from '@/components/table/column'
import { MsgError, MsgSuccess } from '@/utils/utils.ts'
import { FormInstance } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

onMounted(() => getDataBaseArticle())

const column = reactive<tableColumn[]>([
  { label: '标题', prop: 'articleName' },
  { label: '摘要', prop: 'articleSummary' },
  { label: '模板', prop: 'templateName' },
  { label: '操作', prop: '', type: 'slot', slotName: 'handleSlot' },
])

type articleItemType = respDataBaseArticle & { templateName: string }
const dataBaseArticles = ref<articleItemType[]>([])
const getDataBaseArticle = async () => {
  const { data } = await reqGetDataBaseArticles()
  dataBaseArticles.value = data
  if (data.length > 0) {
    dataBaseArticles.value.map(async (item) => {
      const { data } = await reqGetDataBaseTemplate({
        id: item.articleTemplate,
      })
      item.templateName = data[0]?.templateName || ''
    })
  }
}

const onDelArticle = async (id: string) => {
  const { code, msg } = await reqDeleteDataBaseArticle(id)
  code === 0 && MsgSuccess(msg || '删除成功')
  code !== 0 && MsgError(msg || '删除失败')
}

const onAddArticle = (article?: respDataBaseArticle) => {
  router.push({ path: '/database/article/add', query: { id: article.id } })
}
</script>

<style scoped lang="scss">
.container {
  background-color: #fff;
  padding: 20px 16px;
  .header {
    padding-bottom: 15px;
  }
}
</style>
